package com.starbaba.weixin.view;

import com.base.common.database.BaseDao;
import com.base.common.database.DaoHelper;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.core.web.constant.WebConstants;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.dictionary.IServiceType;
import com.starbaba.system.user.model.UserVO;
import com.starbaba.util.QueryListUtil;
import com.starbaba.weixin.model.*;
import com.starbaba.weixin.service.WeixinActivityRedpackService;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Yukinomiu
 * @version 1.0
 */
public class WeixinActivityRedpackAction extends ActionSupport implements ModelDriven {

    private static final long serialVersionUID = 6177379091909988879L;

    private static final String LOGGER_NAME = WeixinActivityRedpackAction.class.getName();

    private Map<String, Object> responseMap = new HashMap<>(3, .75F);

    public Map<String, Object> getResponseMap() {
        return responseMap;
    }

    private List<NameIdVO> activityList;

    public List<NameIdVO> getActivityList() {
        return activityList;
    }

    public List<NameIdVO> activityGroupList;

    public List<NameIdVO> getActivityGroupList() {
        return activityGroupList;
    }

    private QueryListUtil.DataTableResponseInfo responseInfo;

    public QueryListUtil.DataTableResponseInfo getResponseInfo() {
        return responseInfo;
    }

    @SuppressWarnings("SpringJavaAutowiredMembersInspection")
    @Autowired
    @Qualifier("WeixinActivityRedpackServiceImpl")
    private WeixinActivityRedpackService service;

    @Override
    public Object getModel() {
        return null;
    }

    public String showListPage() {
        BaseDao baseDao = new BaseDao(Constant.POOL_LIFE);

        try {
            activityList = baseDao.list("select id, name from weixin_redpack_activity", NameIdVO.class, (Object[]) null);
            activityGroupList = baseDao.list("select id, name from weixin_redpack_activity_group", NameIdVO.class, (Object[]) null);

            if (activityList == null) activityList = new ArrayList<>(0);
            if (activityGroupList == null) activityGroupList = new ArrayList<>(0);
        } catch (AppException e) {
            LogService.error(LOGGER_NAME + ": 获取微信红包活动列表异常: " + e);
        }

        return SUCCESS;
    }

    public String addActivityGroup() {
        Map<String, Object> params = QueryListUtil.getRequestParamsMap(ServletActionContext.getRequest());
        QueryListUtil.dropEmptyParams(params);

        String groupNameStr = (String) params.get("groupName");

        String groupName;
        if (StringUtils.isBlank(groupNameStr)) {
            responseMap.put("status", -1);
            responseMap.put("msg", "参数错误");
            return SUCCESS;
        }
        else {
            groupName = groupNameStr.trim();
        }

        try {
            BaseDao baseDao = new BaseDao(Constant.POOL_LIFE);
            WeixinActivityRedpackGroup existVO = baseDao.get("select * from weixin_redpack_activity_group where name = ?", WeixinActivityRedpackGroup.class, groupName);
            if (existVO != null) {
                responseMap.put("status", 2);
                responseMap.put("msg", "活动类型 [" + groupNameStr + "] 已存在, 不能重复创建");
                return SUCCESS;
            }

            // 保存活动类型
            WeixinActivityRedpackGroup group = new WeixinActivityRedpackGroup();
            group.setName(groupName);
            baseDao.add(group);
        } catch (Exception e) {
            LogService.error(LOGGER_NAME + ": 添加活动类型异常", e);
            responseMap.put("status", 0);
            responseMap.put("msg", "服务器错误");
            return SUCCESS;
        }

        responseMap.put("status", 1);
        responseMap.put("msg", "添加成功");
        return SUCCESS;
    }

    public String addActivity() {
        Map<String, Object> params = QueryListUtil.getRequestParamsMap(ServletActionContext.getRequest());
        QueryListUtil.dropEmptyParams(params);

        String activityGroupStr = (String) params.get("activityGroup");
        String activityNameStr = (String) params.get("activityName");
        String moneyStr = (String) params.get("money");
        String redpackTypeStr = (String) params.get("redpackType");

        Long activityGroup;
        String activityName;
        Integer money;
        Integer redpackType;
        Integer expireDays;
        String channel;

        if (StringUtils.isBlank(activityGroupStr) || StringUtils.isBlank(activityNameStr) || StringUtils.isBlank(moneyStr) || StringUtils.isBlank(redpackTypeStr)) {
            responseMap.put("status", -1);
            responseMap.put("msg", "参数错误");
            return SUCCESS;
        }
        else {
            activityGroup = Long.parseLong(activityGroupStr.trim());
            activityName = activityNameStr.trim();

            double moneyDouble = Double.parseDouble(moneyStr.trim());
            money = new BigDecimal(moneyDouble * 100).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();

            redpackType = Integer.valueOf(redpackTypeStr);
            expireDays = 30;
            channel = activityName;
        }

        try {
            BaseDao baseDao = new BaseDao(Constant.POOL_LIFE);

            WeixinActivityRedpackGroup group = baseDao.get("select * from weixin_redpack_activity_group where id = ?", WeixinActivityRedpackGroup.class, activityGroup);
            if (group == null) {
                responseMap.put("status", 2);
                responseMap.put("msg", "活动类型ID [" + activityGroup + "] 不存在, 请首先创建活动类型再创建活动");
                return SUCCESS;
            }

            RedpackActivityVO existVO = baseDao.get("select * from weixin_redpack_activity where name = ?", RedpackActivityVO.class, activityName);
            if (existVO != null) {
                responseMap.put("status", 2);
                responseMap.put("msg", "活动 [" + activityName + "] 已存在, 不能重复创建活动");
                return SUCCESS;
            }

            if (redpackType.equals(0)) {
                // 普通红包

                // 创建活动
                RedpackActivityVO redpackActivityVO = new RedpackActivityVO()
                        .setName(activityName)
                        .setMoney(money)
                        .setType(redpackType)
                        .setGroupId(group.getId())
                        .setAdRedpackId(null)
                        .setExpireDays(expireDays)
                        .setChannel(channel)
                        .setSendName("车主无忧")
                        .setWishing("恭喜发财")
                        .setRemark(null)
                        .setStatus(1);
                baseDao.add(redpackActivityVO);
            }
            else {
                responseMap.put("status", 3);
                responseMap.put("msg", "红包类型错误");
                return SUCCESS;
            }
        } catch (Exception e) {
            LogService.error(LOGGER_NAME + ": 添加活动异常", e);
            responseMap.put("status", 0);
            responseMap.put("msg", "服务器错误");
            return SUCCESS;
        }

        responseMap.put("status", 1);
        responseMap.put("msg", "添加成功");
        return SUCCESS;
    }

    public String preSend() {
        Map<String, Object> params = QueryListUtil.getRequestParamsMap(ServletActionContext.getRequest());
        QueryListUtil.dropEmptyParams(params);

        String phones = (String) params.get("phones");
        String activity = (String) params.get("activity");

        String[] phoneArray;
        Long activityId;
        if (StringUtils.isBlank(phones) || StringUtils.isBlank(activity)) {
            responseMap.put("status", -1);
            responseMap.put("msg", "参数错误");
            return SUCCESS;
        }
        else {
            phoneArray = phones.split(",");
            activityId = Long.parseLong(activity.trim());
        }

        List<String> passList = new LinkedList<>();
        List<String> failList = new LinkedList<>();
        RedpackActivityVO activityVO;
        WeixinActivityRedpackGroup groupVO;
        try {
            BaseDao baseDao = new BaseDao(Constant.POOL_LIFE);

            activityVO = baseDao.get("select * from weixin_redpack_activity where id = ? and status = 1", RedpackActivityVO.class, activityId);
            if (activityVO == null) {
                responseMap.put("status", 2);
                responseMap.put("msg", "活动不存在");
                return SUCCESS;
            }

            groupVO = baseDao.get("select * from weixin_redpack_activity_group where id = ?", WeixinActivityRedpackGroup.class, activityVO.getGroupId());
            if (groupVO == null) {
                responseMap.put("status", 2);
                responseMap.put("msg", "活动类型ID [" + activityVO.getId() + "] 不存在");
                return SUCCESS;
            }

            if (activityVO.getType().equals(0)) {
                // 普通红包
                for (String phone : phoneArray) {
                    phone = phone.trim();
                    if (!StringUtils.isNumeric(phone)) {
                        responseMap.put("status", -1);
                        responseMap.put("msg", "手机号码错误");
                        return SUCCESS;
                    }
                    Integer count = baseDao.getInt("select count(*) from weixin_redpack_activity_record r where r.activityid = ? and r.phone = ?", activityVO.getId(), phone);
                    if (count != 0) {
                        failList.add(phone);
                    }
                    else {
                        passList.add(phone);
                    }
                }
            }
            else {
                responseMap.put("status", 3);
                responseMap.put("msg", "活动类型不支持");
                return SUCCESS;
            }

            responseMap.put("status", 1);
            responseMap.put("msg", "处理成功");

            responseMap.put("activity", activityVO);
            responseMap.put("pass", passList);
            responseMap.put("fail", failList);
            return SUCCESS;
        } catch (Exception e) {
            LogService.error(LOGGER_NAME + ": 预发红包异常", e);
            responseMap.put("status", 0);
            responseMap.put("msg", "服务器错误: " + e.getMessage());
            return SUCCESS;
        }
    }

    public String send() {
        Map<String, Object> params = QueryListUtil.getRequestParamsMap(ServletActionContext.getRequest());
        QueryListUtil.dropEmptyParams(params);

        String phones = (String) params.get("phones");
        String activity = (String) params.get("activity");
        String remark = (String) params.get("remark");

        String[] phoneArray;
        Long activityId;
        if (StringUtils.isBlank(phones) || StringUtils.isBlank(activity)) {
            responseMap.put("status", -1);
            responseMap.put("msg", "参数错误");
            return SUCCESS;
        }
        else {
            phoneArray = phones.split(",");
            activityId = Long.parseLong(activity.trim());
        }

        int sendCount = 0;
        try {
            BaseDao baseDao = new BaseDao(Constant.POOL_LIFE);

            UserVO user = (UserVO) ServletActionContext.getRequest().getSession().getAttribute(WebConstants.SESSION_ATTRIBUTE_USER);
            String currentUserId = user.getUserid();

            RedpackActivityVO activityVO = baseDao.get("select * from weixin_redpack_activity where id = ? and status = 1", RedpackActivityVO.class, activityId);
            if (activityVO == null) {
                responseMap.put("status", 2);
                responseMap.put("msg", "活动不存在");
                return SUCCESS;
            }

            WeixinActivityRedpackGroup groupVO = baseDao.get("select * from weixin_redpack_activity_group where id = ?", WeixinActivityRedpackGroup.class, activityVO.getGroupId());
            if (groupVO == null) {
                responseMap.put("status", 2);
                responseMap.put("msg", "活动类型ID [" + activityVO.getId() + "] 不存在");
                return SUCCESS;
            }

            if (activityVO.getType().equals(0)) {
                // 普通红包
                DaoHelper.startTransaction();
                try {
                    for (String phone : phoneArray) {
                        phone = phone.trim();
                        if (!StringUtils.isNumeric(phone)) {
                            throw new IllegalArgumentException("手机号码错误");
                        }
                        // 一个活动一个号码只能领取1次
                        Integer count = baseDao.getInt("select count(*) from weixin_redpack_activity_record r where r.phone = ? and r.name = ?", phone, activityVO.getName());
                        if (count != 0) {
                            LogService.info(LOGGER_NAME + ": 发放红包失败, 每个活动用户领取红包次数超过限制, 用户手机号码: " + phone + ", 活动名称: " + activityVO.getName());
                            continue;
                        }
                        else {
                            sendCount++;
                        }

                        // 创建红包
                        Weixin_Redpack_Record record = new Weixin_Redpack_Record()
                                .setProduct("0") // 产品ID为车主无忧
                                .setMoney((long) activityVO.getMoney())
                                .setType(0) // 正常红包, 非补发
                                .setStatus(0)
                                .setPhone(phone)
                                .setDeviceId(null)
                                .setService("xmiles-manager")
                                .setSendName(activityVO.getSendName())
                                .setActivityName(activityVO.getName())
                                .setWishing(activityVO.getWishing())
                                .setRemark(remark)
                                .setServiceType(String.valueOf(IServiceType.CPS_OPERATION_BUFA))
                                .setBusinessId("000000000000000")
                                .setCreateTime(new Date());
                        long redpackRecordId = baseDao.addReturnGeneratedKey(record);

                        // 创建记录
                        RedpackActivityRecordVO recordVO = new RedpackActivityRecordVO()
                                .setOperator(currentUserId)
                                .setRemark(remark)
                                .setCreateTime(new Date())
                                .setPhone(phone)
                                .setMoney(activityVO.getMoney())
                                .setName(activityVO.getName())
                                .setGroup(groupVO.getName())
                                .setType(activityVO.getType())
                                .setRedpackRecordId(redpackRecordId)
                                .setActivityId(activityVO.getId())
                                .setGroupId(groupVO.getId());
                        long recordVOId = baseDao.addReturnGeneratedKey(recordVO);
                        
                        record.setBusinessId(Long.valueOf(recordVOId).toString());
                        record.setId(redpackRecordId);
                        baseDao.update(record, "id");
                    }
                    DaoHelper.commitTransaction();
                } catch (Exception e) {
                    DaoHelper.rollbackTransaction();
                    throw e;
                }
            }
            else {
                responseMap.put("status", 3);
                responseMap.put("msg", "活动类型不支持");
                return SUCCESS;
            }

            responseMap.put("status", 1);
            responseMap.put("msg", "发放红包成功, 共发出 " + sendCount + " 个红包");
            return SUCCESS;
        } catch (Exception e) {
            LogService.error(LOGGER_NAME + ": 发放红包错误", e);
            responseMap.put("status", 0);
            responseMap.put("msg", "服务器错误: " + e.getMessage());
            return SUCCESS;
        }
    }

    public String getRecord() {
        Map<String, Object> params = QueryListUtil.getRequestParamsMap(ServletActionContext.getRequest());
        QueryListUtil.dropEmptyParams(params);

        Map<String, Object> queryParams = new HashMap<>();
        Integer echo;
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 查询参数
            if (params.get("startDate") != null) {
                queryParams.put("startDate", sdf.parse((String) params.get("startDate")));
            }
            if (params.get("endDate") != null) {
                Date endDate = sdf.parse((String) params.get("endDate"));
                c.setTime(endDate);
                c.set(Calendar.HOUR_OF_DAY, 23);
                c.set(Calendar.MINUTE, 59);
                c.set(Calendar.SECOND, 59);
                c.set(Calendar.MILLISECOND, 0);
                queryParams.put("endDate", c.getTime());
            }
            if (params.get("sType") != null) {
                queryParams.put("type", Integer.valueOf((String) params.get("sType")));
            }
            if (params.get("sActivity") != null) {
                queryParams.put("activity", params.get("sActivity"));
            }
            if (params.get("group") != null) {
                queryParams.put("group", params.get("group"));
            }
            if (params.get("phone") != null) {
                queryParams.put("phone", params.get("phone"));
            }
            if (params.get("activityId") != null) {
                queryParams.put("activityId", params.get("activityId"));
            }
            if (params.get("groupId") != null) {
                queryParams.put("groupId", params.get("groupId"));
            }

            // 表单控件参数
            QueryListUtil.DataTableRequestInfo info = QueryListUtil.getDataTableRequestInfo(params);

            echo = info.getEcho();

            Integer start = info.getStart();
            Integer limit = info.getLimit();

            queryParams.put("start", start);
            queryParams.put("limit", limit);
        } catch (Exception e) {
            LogService.info(LOGGER_NAME + ": 请求解析异常: " + e.getMessage());
            return SUCCESS;
        }

        try {
            QueryListVO result = service.getRecord(queryParams);
            responseInfo = QueryListUtil.getDataTableResponseInfo(echo, result.getTotalCount(), result.getList());
        } catch (Exception e) {
            LogService.error(LOGGER_NAME + ": 查询数据库异常: " + e.getMessage());
            return SUCCESS;
        }
        return SUCCESS;
    }
}
